<template>
	<xn-form-container title="短信详情" width="60%" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="手机号" name="phone">
						<a-input v-model:value="searchFormState.phone" placeholder="请输入手机号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="发送状态" name="detailStatus">
						<a-select
							v-model:value="searchFormState.detailStatus"
							placeholder="请选择批次状态"
							:options="smsDetailStatusOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-space>
						<a-button type="primary" @click="tableRef.refresh(true)">查询</a-button>
						<a-button @click="searchFormRef.resetFields()">重置</a-button>
						<a-button type="primary" @click="exportList" :loading="exportLoading"> 导出</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:pagination="false"
			:row-key="(record) => record.id"
			:scroll="{ x: 'max-content' }"
		>
			<template #sendStatusName="{ text }">
				<span :style="{ color: text === '发送成功' ? '#52c41a' : '#ff4d4f', fontWeight: 500 }">
					{{ text }}
				</span>
			</template>
			<template #messageContent="{ text }">
				<a-tooltip :title="text">
					<div class="ellipsis-text">
						{{ text.length > 30 ? text.slice(0, 30) + '...' : text }}
					</div>
				</a-tooltip>
			</template>
			<template #supplierName="{ text }">
				<span>{{ text }}</span>
			</template>
			<template #currentChannel="{ record }">
				<a-popover v-model:visible="record.popoverVisible" trigger="click" placement="top">
					<template #content>
						<pre v-if="record.popoverData">{{ record.popoverData }}</pre>
						<p v-else>加载中...</p>
					</template>
					<a-tag
						v-if="record.supplierCode && record.supplierOrder"
						:color="getSupplierPosition(record.supplierCode, record.supplierOrder) === 0 ? 'green' : 'blue'"
						@click="fetchPopoverData(record)"
					>
						第{{ getSupplierPosition(record.supplierCode, record.supplierOrder) + 1 }}路由
					</a-tag>
				</a-popover>
			</template>
		</s-table>
	</xn-form-container>
</template>

<script setup>
	import smsBatchApi from '@/api/tjzy/sms/smsBatchApi'
	import tool from '@/utils/tool'
	import smsRecordApi from '@/api/tjzy/sms/smsReceiptApi'
	import { yzErrorCode } from '@/utils/smsErrorCode'
	import downloadUtil from '@/utils/downloadUtil'

	const emit = defineEmits({ successful: null })
	const smsDetailStatusOptions = tool.dictList('SMSDetailStatus')
	const visible = ref(false)
	const searchFormRef = ref()
	const tableRef = ref()
	const exportLoading = ref(false)

	const columns = [
		{
			title: '手机号',
			dataIndex: 'toPhone',
			align: 'center'
		},
		{
			title: '发送状态',
			dataIndex: 'sendStatusName',
			slots: { customRender: 'sendStatusName' },
			align: 'center'
		},
		{
			title: '短信内容',
			dataIndex: 'messageContent',
			width: 20,
			ellipsis: {
				showTitle: true
			},
			slots: { customRender: 'messageContent' },
			align: 'center'
		},
		{
			title: '供应商',
			dataIndex: 'supplierName',
			slots: { customRender: 'supplierName' },
			align: 'center'
		},
		{
			title: '当前路由',
			dataIndex: 'currentChannel',
			slots: { customRender: 'currentChannel' },
			align: 'center'
		}
	]
	const searchFormState = ref({
		batchNumber: undefined,
		phone: undefined
	})

	// 打开抽屉
	const openDetail = (record) => {
		visible.value = true
		searchFormState.value.batchNumber = record.batchNumber
	}

	const loadData = (parameter) => {
		searchFormState.value.current = parameter.current
		searchFormState.value.size = parameter.size
		return smsBatchApi.pageDetail(searchFormState.value).then((res) => {
			// 为每条记录添加 popoverVisible 和 popoverData 属性
			res.records.forEach((record) => {
				record.popoverVisible = false
				record.popoverData = null
			})
			return res
		})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		emit('successful')
	}

	const exportList = () => {
		exportLoading.value = true
		smsBatchApi
			.exportDetail(searchFormState.value)
			.then((res) => {
				downloadUtil.resultDownload(res)
			})
			.finally(() => {
				exportLoading.value = false
			})
	}

	// 获取供应商位置
	const getSupplierPosition = (supplierCode, supplierOrder) => {
		const orderArray = supplierOrder.split(',')
		return orderArray.indexOf(supplierCode)
	}

	// 查询 popover 数据
	const fetchPopoverData = async (record) => {
		record.popoverVisible = true
		smsRecordApi
			.getSendDetail(searchFormState.value.batchNumber, record.noSensitivePhone)
			.then((res) => {
				// 如果供应商是越众，尝试解析错误码
				if (record.supplierName === '越众') {
					// 查找匹配的错误码
					const errorCode = yzErrorCode.find((item) => res.includes(item.code))
					if (errorCode) {
						record.popoverData = `第1路由: ${record.supplierName}: ${errorCode.label}`
						return
					}
				}
				// 如果返回的数据为空
				if (res === '') {
					// 直接拼接“第1路由”和“供应商名称：尚未返回数据”
					record.popoverData = `第1路由: ${record.supplierName}：尚未返回数据`
				} else {
					// 如果返回的数据不为空，处理每一行
					// 按换行符分割字符串
					const lines = res.split(/\r?\n/)
					// 为每一行添加前缀
					const processedLines = lines.map((line, index) => {
						return `第${index + 1}路由: ${line}`
					})
					// 重新拼接字符串
					res = processedLines.join('\n')
					// 如果发送状态为 '1'，在最后添加一条特殊信息
					if (record.sendStatus === '1') {
						// 获取当前行数
						const currentLineCount = res.split(/\r?\n/).length
						// 添加特殊信息，并在前面加上“第n路由”
						res += `\n第${currentLineCount + 1}路由: ${record.supplierName}：尚未返回数据`
					}
					// 设置 popoverData
					record.popoverData = res
				}
			})
			.catch((error) => {
				console.error('Failed to fetch popover data:', error)
				record.popoverData = '加载失败' // 存储错误信息
			})
	}

	defineExpose({
		openDetail
	})
</script>

<style scoped>
	.ellipsis-text {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>
